package com.ztgf.shopping.api.client.shop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.request.ContractDownloadRequest;
import com.qiyuesuo.sdk.v2.utils.IOUtils;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.logistics.models.dto.deppon.LogisticsUserContractDTO;
import com.ztgf.logistics.models.dto.deppon.LogisticsUserDTO;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserContractService;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserService;
import com.ztgf.shopping.models.bo.shop.ShopContractSettleInUpdateBO;
import com.ztgf.shopping.models.dto.shop.ShopContractSettleInDTO;
import com.ztgf.shopping.models.service.shop.IShopContractSettleInService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 入住协议控制器
 *
 * @author zhanghualang
 * @Date 2020-07-30 10:47:50
 */

@RestController
@RequestMapping("/api/shopContractSettleIn")
@Slf4j
@Api(value = "ShopContractSettleInApiController",tags = "入住协议Api接口")
public class ShopContractSettleInApiController {

    @Value("${shop.qiyuesuo.service.sdkUrl}")
    private String serverUrl;

    @Value("${shop.qiyuesuo.service.appToken}")
    private String accessKey;

    @Value("${shop.qiyuesuo.service.appSecret}")
    private String accessSecret;

    @DubboReference
    private IShopContractSettleInService shopContractSettleInService;
    @DubboReference
    private ILogisticsUserContractService iLogisticsUserContractService;
    @DubboReference
    private ILogisticsUserService logisticsUserService;
    @PostMapping("/get")
    @ApiOperation(value = "根据店铺ID查找",notes = "根据店铺ID查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<ShopContractSettleInDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        Wrapper<ShopContractSettleInDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", id);
        ShopContractSettleInDTO dto = shopContractSettleInService.selectOne(wrapper);
        if (dto != null && dto.getId() != null){
            return new Result<>(dto);
        }else{
            return new Result<>(CodeEnum.FAIL_100042);
        }
    }

    @PostMapping("/createContract")
    @ApiOperation(value = "根据店铺ID生成入住合同",notes = "根据店铺ID生成入住合同")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result createContract(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        boolean flag = shopContractSettleInService.createShopContract(id);
        if (flag){
            return new Result<>();
        }else {
            return new Result<>(CodeEnum.FAIL);
        }
    }


    @PostMapping("/gerenateSignUrl")
    @ApiOperation(value = "根据店铺ID获取合同签订地址",notes = "根据店铺ID获取合同签订地址")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result gerenateSignUrl(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        String url = "";
        try {
            url = shopContractSettleInService.gerenateSignUrl(id); //获取合同签订地址
        } catch (Exception e) {
            log.info(e.getMessage());
        }

        if ("".equals(url)){
            return new Result<>(CodeEnum.FAIL);
        }else {
            return new Result<>(url);
        }
    }



    @PostMapping("/getCallBackContactInfo")
    public String getCallBackContactInfo(@RequestParam(required = false) String content,@RequestParam(required = false) String signature,@RequestParam(required = false) String timestamp) throws Exception {
        return shopContractSettleInService.updateContactByCallBackInfo(signature, timestamp, content);
    }



    @PostMapping("/getContactUrl")
    @ApiOperation(value = "查看合同",notes = "查看合同")
    @ApiImplicitParam(name = "contractId",value = "contractId 契约锁合同id",required = true,paramType = "query", dataType = "Long")
    public Result<String> getContactUrl(Long contractId){
        String contractString = shopContractSettleInService.getContractString(contractId);
        return new Result<>(contractString);
    }

    /**
     * 根据店铺id下载合同
     * @return
     */
    @GetMapping("/settleContractDownload/{shopId}")
    public void settleContractDownload(@PathVariable("shopId") Long shopId, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;fileName=" + shopId + ".zip");
        ShopContractSettleInDTO shopContractSettleInDTO = shopContractSettleInService.getByShopId(shopId);
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 下载合同
        ContractDownloadRequest request = new ContractDownloadRequest(Long.parseLong(shopContractSettleInDTO.getContractLockId()));
        List<String> str = new ArrayList<>();
        str.add("CONTRACT");
        request.setDownloadItems(str);
        log.info(request.getUrl());
        OutputStream fos = response.getOutputStream();
        //FileOutputStream fos = new FileOutputStream("E:/module/doc.zip");
        sdkClient.download(request, fos);
        IOUtils.safeClose(fos);
        log.info("下载合同成功");
    }

    /**
     * 根据店铺id下载德邦合同
     * @return
     */
    @GetMapping("/settleContractDBDownload/{id}")
    public void settleContractDBDownload(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;fileName=" + id + ".zip");
       // ShopContractSettleInDTO shopContractSettleInDTO = shopContractSettleInService.getByShopId(shopId);

        LogisticsUserContractDTO logisticsUserContractDTO = iLogisticsUserContractService.selectById(id);
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 下载合同
        ContractDownloadRequest request = new ContractDownloadRequest(Long.parseLong(logisticsUserContractDTO.getContractId()));
        List<String> str = new ArrayList<>();
        str.add("CONTRACT");
        request.setDownloadItems(str);
        log.info(request.getUrl());
        OutputStream fos = response.getOutputStream();
        //FileOutputStream fos = new FileOutputStream("E:/module/doc.zip");
        sdkClient.download(request, fos);
        IOUtils.safeClose(fos);
        log.info("下载合同成功");
    }


    @PostMapping("/updateByLogisticsUserContractId")
    @ApiOperation(value = "到期续约", notes = "到期续约")
    public Result updateByShopId(ShopContractSettleInUpdateBO bo) {
        if (bo.getId() == null || null == bo.getEndDate()) {
            return new Result(CodeEnum.FAIL_100002);
        }
        boolean b=true;
        LogisticsUserContractDTO logisticsUserContractDTO = iLogisticsUserContractService.selectById(bo.getId());
        LogisticsUserDTO logisticsUserDTO = logisticsUserService.selectById(logisticsUserContractDTO.getShopId());
        log.info("================date=="+DateUtils.getCurrentDateTime().compareTo(bo.getEndDate()));
        if ((DateUtils.getCurrentDateTime().compareTo(bo.getEndDate())) >0){
            logisticsUserDTO.setStatus(1);
            b = logisticsUserService.updateById(logisticsUserDTO);
        }else {
            logisticsUserDTO.setStatus(0);
            logisticsUserContractDTO.setEndDate(DateUtils.dateFormat(bo.getEndDate(),DateUtils.DATE_FORMAT_DATETIME));
            log.info("========================="+bo.getEndDate());
            log.info("=========================logisticsUserContractDTO"+logisticsUserContractDTO);
            boolean flag = iLogisticsUserContractService.updateById(logisticsUserContractDTO);
            log.info("=========================flag"+flag);
            b = logisticsUserService.updateById(logisticsUserDTO);
        }
       // LogisticsUserContractDTO dto = new LogisticsUserContractDTO();
       // logisticsUserContractDTO.setEndDate(bo.getEndDate());
        //dto.setId(bo.getId());
        //dto.setExpireStatus(0); // 到期状态 0正常，1即将到期，2已过期
        if (b){
            return new Result<>();
        }else{
            return new Result<>(CodeEnum.FAIL);
        }
    }
}
